package com.example.a12769.myapplication
import android.support.v4.app.Fragment
import android.widget.RadioGroup
import com.example.a12769.myapplication.base.activity.BaseActiviy
import com.example.a12769.myapplication.base.fragment.BaseFragment
import com.example.a12769.myapplication.home.HomeFragment
import java.util.ArrayList
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : BaseActiviy() {
    private lateinit var mFragments: ArrayList<BaseFragment>
    //上次显示的fragment
    private var tempFragment: BaseFragment? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        initFragment()
    }

    private fun initFragment() {
        mFragments = ArrayList<BaseFragment>()
        mFragments.add(HomeFragment())
        mFragments.add(HomeFragment())
        mFragments.add(HomeFragment())
        mFragments.add(HomeFragment())
    }

    private var position: Int=0
    override fun initLisenner() {
        rg_main.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_home//主页
                -> position = 0
                R.id.rb_community//发现
                -> position = 2
                R.id.rb_cart//购物车
                -> position = 1
                R.id.rb_user//用户中心
                -> position = 3
                else -> position = 0
            }
            //根据位置的区不同的Fragment
            val baseFragment = getFragment(position)
            //第一个参数是上一次显示的
            //第二个参数是当前正要显示的
            switchFragment(tempFragment, baseFragment)
        })
        rg_main.check(R.id.rb_home)
    }

    private fun switchFragment(fromFragment: Fragment?, nextFragment: BaseFragment?) {
        if (tempFragment !== nextFragment) {
            tempFragment = nextFragment
            if (nextFragment != null) {
                val transation = supportFragmentManager.beginTransaction()
                //判断nextFragment是否添加
                if (!nextFragment.isAdded) {
                    //隐藏当前Fragment
                    if (fromFragment != null) {
                        transation.hide(fromFragment)
                    }
                    transation.add(R.id.frameLayout, nextFragment).commit()
                } else {
                    //隐藏当前的Fragmeent
                    if (fromFragment != null) {
                        transation.hide(fromFragment)
                    }
                    transation.show(nextFragment).commit()
                }
            }
        }
    }
    private fun getFragment(position: Int): BaseFragment? {
        return if (mFragments != null && mFragments.size > 0) {
            mFragments[position]
        } else null
    }
    override fun initData() {

    }
}
